<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
<!-----------------------------------------------------------------------
- Copyright (C) 2025, iwyxdxl
- Licensed under GNU GPL-3.0 or higher, see the LICENSE file for details.
-
- This file is part of WeChatBot.
- WeChatBot is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- WeChatBot is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with WeChatBot.  If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------>
    <title>{{ character_name }} 的小号</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #ffffff;
            color: #333;
            line-height: 1.4;
        }

        /* 顶部状态栏 */
        .status-bar {
            background: #000;
            color: white;
            padding: 8px 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 14px;
            font-weight: 500;
        }

        .status-left {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .back-arrow {
            font-size: 18px;
            cursor: pointer;
        }

        /* 个人资料头部 */
        .profile-header {
            background: white;
            padding: 20px 16px;
            border-bottom: 1px solid #e1e8ed;
        }

        .profile-top {
            display: flex;
            align-items: flex-start;
            margin-bottom: 16px;
        }

        .profile-avatar {
            width: 72px;
            height: 72px;
            border-radius: 50%;
            background: linear-gradient(45deg, #1da1f2, #0d8bd9);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32px;
            color: white;
            margin-right: 16px;
            flex-shrink: 0;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            position: relative;
            cursor: pointer;
        }

        .profile-avatar:hover::after {
            content: '📷';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 4px;
            border-radius: 4px;
            font-size: 16px;
        }

        .avatar-edit-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .avatar-edit-modal {
            background: white;
            border-radius: 12px;
            padding: 24px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
        }

        .avatar-edit-modal h3 {
            margin: 0 0 16px 0;
            font-size: 18px;
            color: #0f1419;
        }

        .avatar-input-group {
            margin-bottom: 16px;
        }

        .avatar-input-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            color: #536471;
            font-weight: 500;
        }

        .avatar-input-group input {
            width: 100%;
            padding: 12px;
            border: 1px solid #cfd9de;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s;
        }

        .avatar-input-group input:focus {
            outline: none;
            border-color: #1da1f2;
        }

        .avatar-preview {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: linear-gradient(45deg, #1da1f2, #0d8bd9);
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            margin: 16px auto;
            border: 2px solid #e1e8ed;
        }

        .avatar-edit-buttons {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
        }

        .avatar-edit-btn {
            padding: 10px 20px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
        }

        .avatar-edit-btn.cancel {
            background: #f7f9fa;
            color: #0f1419;
            border: 1px solid #cfd9de;
        }

        .avatar-edit-btn.cancel:hover {
            background: #e1e8ed;
        }

        .avatar-edit-btn.save {
            background: #1da1f2;
            color: white;
        }

        .avatar-edit-btn.save:hover {
            background: #0d8bd9;
        }

        .avatar-edit-btn.save:disabled {
            background: #aab8c2;
            cursor: not-allowed;
        }

        .avatar-edit-btn.clear {
            background: #e0245e;
            color: white;
        }

        .avatar-edit-btn.clear:hover {
            background: #c01e4e;
        }

        .profile-info {
            flex: 1;
            min-width: 0;
        }

        .profile-name {
            font-size: 20px;
            font-weight: 700;
            color: #0f1419;
            margin-bottom: 4px;
            line-height: 1.2;
        }

        .profile-handle {
            font-size: 15px;
            color: #536471;
            margin-bottom: 12px;
        }

        .profile-bio {
            font-size: 15px;
            color: #0f1419;
            margin-bottom: 12px;
            line-height: 1.4;
        }

        .profile-location {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 15px;
            color: #536471;
            margin-bottom: 12px;
        }

        .location-icon {
            font-size: 16px;
        }

        .profile-stats {
            display: flex;
            gap: 20px;
            font-size: 15px;
            color: #536471;
        }

        .stat-item {
            cursor: pointer;
        }

        .stat-item:hover {
            text-decoration: underline;
        }

        .edit-profile-btn {
            background: transparent;
            border: 1px solid #cfd9de;
            border-radius: 20px;
            padding: 8px 16px;
            font-size: 15px;
            font-weight: 600;
            color: #0f1419;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .edit-profile-btn:hover {
            background-color: #f7f9fa;
        }

        /* 导航标签 */
        .nav-tabs {
            display: flex;
            background: white;
            border-bottom: 1px solid #e1e8ed;
        }

        .nav-tab {
            flex: 1;
            padding: 16px;
            text-align: center;
            font-size: 15px;
            font-weight: 500;
            color: #536471;
            cursor: pointer;
            transition: all 0.2s;
            border-bottom: 2px solid transparent;
        }

        .nav-tab.active {
            color: #0f1419;
            border-bottom-color: #1da1f2;
        }

        .nav-tab:hover {
            background-color: #f7f9fa;
        }

        /* 帖子流 */
        .posts-container {
            background: white;
        }

        .post {
            padding: 16px;
            border-bottom: 1px solid #e1e8ed;
            transition: background-color 0.2s;
        }

        .post:hover {
            background-color: #f7f9fa;
        }

        .post-content-wrapper {
            display: flex;
            gap: 12px;
        }

        .post-avatar {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            background: linear-gradient(45deg, #1da1f2, #0d8bd9);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: white;
            flex-shrink: 0;
        }

        .post-main {
            flex: 1;
            min-width: 0;
        }

        .post-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 4px;
        }

        .post-author {
            font-weight: 700;
            color: #0f1419;
            font-size: 15px;
        }

        .post-handle {
            color: #536471;
            font-size: 15px;
        }

        .post-time {
            color: #536471;
            font-size: 15px;
        }

        .post-content {
            font-size: 15px;
            color: #0f1419;
            line-height: 1.5;
            margin-bottom: 12px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .post-actions {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .action-btn {
            display: flex;
            align-items: center;
            gap: 6px;
            color: #536471;
            font-size: 13px;
            cursor: pointer;
            transition: color 0.2s;
            background: none;
            border: none;
            padding: 0;
        }

        .action-btn:hover {
            color: #1da1f2;
        }

        .action-btn.like:hover {
            color: #e0245e;
        }
        .action-btn.like.liked {
            color: #e0245e;
        }

        .action-btn.retweet:hover {
            color: #17bf63;
        }

        .action-icon {
            font-size: 18px;
        }

        /* 控制区域 */
        .controls {
            padding: 16px;
            background: white;
            border-bottom: 1px solid #e1e8ed;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .status-text {
            color: #536471;
            font-size: 15px;
        }

        .refresh-btn {
            background: #1da1f2;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        .refresh-btn:hover {
            background-color: #1a8cd8;
        }

        .refresh-btn:disabled {
            background-color: #aab8c2;
            cursor: not-allowed;
        }

        /* 空状态 */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #536471;
        }

        .empty-icon {
            font-size: 48px;
            margin-bottom: 16px;
            opacity: 0.5;
        }

        .empty-title {
            font-size: 20px;
            font-weight: 700;
            color: #0f1419;
            margin-bottom: 8px;
        }

        .empty-description {
            font-size: 15px;
            color: #536471;
        }

        /* 加载状态 */
        .loading {
            text-align: center;
            padding: 40px;
            color: #536471;
        }

        .spinner {
            display: inline-block;
            width: 24px;
            height: 24px;
            border: 2px solid #e1e8ed;
            border-top: 2px solid #1da1f2;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-bottom: 12px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 新帖子动画 */
        .new-post-animation {
            animation: slideInUp 0.3s ease-out;
        }

        @keyframes slideInUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .profile-header {
                padding: 16px;
            }
            
            .profile-avatar {
                width: 64px;
                height: 64px;
                font-size: 28px;
            }
            
            .profile-name {
                font-size: 18px;
            }
            
            .nav-tab {
                padding: 12px 8px;
                font-size: 14px;
            }
            
            .post {
                padding: 12px 16px;
            }
            
            .post-avatar {
                width: 40px;
                height: 40px;
                font-size: 18px;
            }
        }

        /* 标签样式 */
        .hashtag {
            color: #1da1f2;
            font-weight: 500;
            text-decoration: none;
        }

        .hashtag:hover {
            text-decoration: underline;
        }

        /* 评论样式 */
        .comments {
            margin-top: 12px;
            padding-top: 12px;
            border-top: 1px solid #e1e8ed;
        }

        .comment {
            background: #f7f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 8px;
        }

        .comment-author {
            font-weight: 600;
            color: #0f1419;
            font-size: 14px;
            margin-bottom: 4px;
        }

        .comment-content {
            font-size: 14px;
            color: #536471;
            line-height: 1.4;
        }

        .comment-time {
            font-size: 12px;
            color: #aab8c2;
            margin-top: 4px;
        }

        /* 二级回复样式 */
        .comment .replies {
            margin-top: 8px;
            padding-left: 12px;
            border-left: 2px solid #e1e8ed;
        }
        .reply-meta {
            font-size: 12px;
            color: #8899a6;
            margin-bottom: 6px;
        }
        .quote-block {
            margin-top: 8px;
            border: 1px solid #e1e8ed;
            background: #fff;
            border-radius: 8px;
            padding: 10px;
        }
        .quote-author { font-weight: 600; color: #0f1419; font-size: 13px; }
        .quote-content { font-size: 13px; color: #536471; margin-top: 4px; }

        /* 就地回复框 */
        .reply-box {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            align-items: flex-start;
        }
        .reply-input {
            flex: 1;
            padding: 10px 12px;
            border: 1px solid #cfd9de;
            border-radius: 8px;
            font-size: 14px;
            resize: vertical;
            min-height: 36px;
            max-height: 120px;
        }
        .reply-actions {
            display: flex;
            gap: 8px;
        }
        .reply-btn {
            background: #1da1f2;
            color: #fff;
            border: none;
            padding: 8px 12px;
            border-radius: 16px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }
        .reply-cancel-btn {
            background: #f7f9fa;
            color: #0f1419;
            border: 1px solid #cfd9de;
            padding: 8px 12px;
            border-radius: 16px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }

        /* 法律声明样式 */
        .legal-notice {
            margin-top: 30px;
            padding: 15px 20px;
            background-color: #f7f8fc;
            border-top: 1px solid #e1e8ed;
            text-align: center;
            font-size: 0.75em;
            color: #8899a6;
            line-height: 1.4;
            width: 100%;
            box-sizing: border-box;
        }
        .legal-notice .legal-toggle {
            cursor: pointer;
            color: #536471;
            font-weight: 500;
            margin-bottom: 8px;
            display: inline-block;
            font-size: 0.85em;
            opacity: 0.7;
            transition: opacity 0.2s;
        }
        .legal-notice .legal-toggle:hover {
            opacity: 1;
            color: #1da1f2;
        }
        .legal-notice .legal-content {
            display: none;
            text-align: left;
            font-size: 0.9em;
            margin-top: 10px;
            padding: 10px;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 8px;
            border: 1px solid #e1e8ed;
        }
        .legal-notice .legal-content a {
            color: #1da1f2;
            text-decoration: none;
        }
        .legal-notice .legal-content a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <!-- 顶部状态栏 -->
    <div class="status-bar">
        <div class="status-left">
            <span class="back-arrow" onclick="window.history.back()">←</span>
            <span id="current-time"></span>
        </div>
        <p style="opacity: 0.5;">论坛功能灵感来源 @白小桃</p>
        <div class="status-right">
            <span>📶</span>
            <span>📶</span>
            <span>52%</span>
        </div>
    </div>

    <!-- 个人资料头部 -->
    <div class="profile-header">
        <div class="profile-top">
            <div class="profile-avatar" id="profileAvatar" onclick="openAvatarEdit()" 
                 data-avatar-url="{{ avatar_url or '' }}">
                {{ character_name[0] if character_name else '' }}
            </div>
            <div class="profile-info">
                <div class="profile-name">{{ character_name }} 的小号</div>
                <div class="profile-handle">@{{ character_name|lower|replace(' ', '_') }}_bot</div>
                <div class="profile-bio">记录内心真实想法的秘密空间</div>
                <div class="profile-location">
                    <span class="location-icon">📍</span>
                    <span>网络空间</span>
                </div>
                <div class="profile-stats">
                    <span class="stat-item">1 正在关注</span>
                    <span class="stat-item">1 关注者</span>
                </div>
            </div>
            <button class="edit-profile-btn">已关注</button>
        </div>
    </div>

    <!-- 导航标签 -->
    <div class="nav-tabs">
        <div class="nav-tab active" onclick="switchTab('posts', event)">发推</div>
        <div class="nav-tab" onclick="switchTab('replies', event)">推文和回复</div>
            <div class="nav-tab" onclick="switchTab('likes', event)">喜欢</div>
    </div>

    <!-- 控制区域 -->
    <div class="controls">
        <div class="status-text" id="status">点击按钮看看{{ character_name }} 有什么新想法</div>
        <div style="display:flex; gap:8px; align-items:center;">
            <button class="refresh-btn" id="refreshBtn" onclick="refreshForum()">✨ 看新动态</button>
            <button class="refresh-btn" id="refreshLikesBtn" onclick="refreshLikes()" style="display:none; background:#f91880;">💖 刷新喜欢</button>
        </div>
    </div>

    <!-- 帖子流 -->
    <div class="posts-container" id="postsContainer">
        <div class="loading" id="loading" style="display: none;">
            <div class="spinner"></div>
            <div>正在获取推特内容...</div>
        </div>
    </div>

    <!-- 头像编辑模态框 -->
    <div class="avatar-edit-overlay" id="avatarEditOverlay">
        <div class="avatar-edit-modal">
            <h3>更换头像</h3>
            <div class="avatar-input-group">
                <label for="avatarFileInput">选择头像图片文件</label>
                <input type="file" id="avatarFileInput" accept="image/png,image/jpeg,image/jpg,image/gif,image/webp" onchange="previewAvatar()" />
                <p style="font-size: 12px; color: #536471; margin-top: 8px;">
                    支持PNG、JPG、JPEG、GIF、WebP格式，文件大小建议不超过5MB
                </p>
            </div>
            <div class="avatar-preview" id="avatarPreview"></div>
            <div class="avatar-edit-buttons">
                <button class="avatar-edit-btn cancel" onclick="closeAvatarEdit()">取消</button>
                <button class="avatar-edit-btn clear" onclick="clearAvatar()">清除头像</button>
                <button class="avatar-edit-btn save" id="saveAvatarBtn" onclick="uploadAvatar()" disabled>上传</button>
            </div>
        </div>
    </div>

    <!-- 法律声明 -->
    <div class="legal-notice">
        <div class="legal-toggle" id="toggleLegal">显示法律声明</div>
        <div class="legal-content" id="legalContent">
            <p>
                Modified based on the <strong>KouriChat</strong> project.<br>
                原项目版权: Copyright (C) 2025, umaru<br>
                修改版本版权: Copyright (C) 2025, iwyxdxl
            </p>
            <p>
                本软件是自由软件，您可以根据 <a href="https://www.gnu.org/licenses/gpl-3.0.zh-cn.html" target="_blank">
                GNU 通用公共许可证 第3版（或更高版本）</a> 的条款重新发布和修改本软件。
            </p>
            <p>
                本软件按"现状"提供，不提供任何明示或暗示的担保（包括适销性或特定用途适用性）。<br>
                如您未收到完整的许可证副本，请访问 <a href="https://www.gnu.org/licenses/gpl-3.0.zh-cn.html" target="_blank">
                GNU GPL 3.0 中文版</a> 获取。
            </p>
            <p>
                源代码获取：<br>
                原项目源代码：<a href="https://github.com/KouriChat/KouriChat" target="_blank">https://github.com/KouriChat/KouriChat</a><br>
                本项目源代码：<a href="https://github.com/iwyxdxl/WeChatBot_WXAUTO_SE" target="_blank">https://github.com/iwyxdxl/WeChatBot_WXAUTO_SE</a>
            </p>
            <p>
                本软件仅供学习和娱乐使用，请勿用于违法用途，否则产生的一切法律责任均与任何作者无关。
            </p>
        </div>
    </div>

    <script>
        const characterName = '{{ character_name }}';
        let isRefreshing = false;
        let currentTab = 'posts';
        
        // 辅助函数：获取CSRF token
        function getCSRFToken() {
            return document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
        }
        window.getCSRFToken = getCSRFToken;
        
        // 辅助函数：获取包含CSRF token的headers
        function getCSRFHeaders(additionalHeaders = {}) {
            const csrfToken = getCSRFToken();
            const headers = { ...additionalHeaders };
            if (csrfToken) {
                headers['X-CSRFToken'] = csrfToken;
            }
            return headers;
        }
        window.getCSRFHeaders = getCSRFHeaders;

        // 更新时间显示
        function updateTime() {
            const now = new Date();
            const timeString = now.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
            document.getElementById('current-time').textContent = timeString;
        }

        // 切换标签
        function switchTab(tabName, event) {
            currentTab = tabName;
            
            // 更新标签状态
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            if (event && event.target) {
                event.target.classList.add('active');
            }
            
            // 加载不同标签内容
            if (tabName === 'posts') {
                loadExistingPosts();
                document.getElementById('refreshLikesBtn').style.display = 'none';
                const rb = document.getElementById('refreshBtn');
                if (rb) rb.style.display = 'inline-block';
                const status = document.getElementById('status');
                if (status) status.textContent = `点击按钮看看${characterName} 有什么新想法`;
            } else if (tabName === 'replies') {
                loadThreads();
                document.getElementById('refreshLikesBtn').style.display = 'none';
                const rb = document.getElementById('refreshBtn');
                if (rb) rb.style.display = 'none'; // 推文和回复页不展示“看新动态”
                const status = document.getElementById('status');
                if (status) status.textContent = '看看围绕这条动态的对话';
            } else if (tabName === 'likes') {
                loadLikes();
                document.getElementById('refreshLikesBtn').style.display = 'inline-block';
                const rb = document.getElementById('refreshBtn');
                if (rb) rb.style.display = 'none';
                const status = document.getElementById('status');
                if (status) status.textContent = '看看他最近喜欢了什么';
            }
            console.log('切换到标签:', tabName);
        }

        // 页面加载时获取现有帖子
        document.addEventListener('DOMContentLoaded', function() {
            console.log('页面加载完成，开始获取帖子');
            console.log('角色名:', characterName);
            updateTime();
            setInterval(updateTime, 60000); // 每分钟更新一次时间
            loadExistingPosts();
            loadAvatarSettings(); // 加载头像设置

            // 委托绑定帖子内按钮事件
            const postsContainer = document.getElementById('postsContainer');
            postsContainer.addEventListener('click', async function(e) {
                // 删除喜欢Feed项
                const delLiked = e.target.closest('.action-btn.delete-btn');
                if (delLiked && delLiked.hasAttribute('data-liked-id')) {
                    const itemId = delLiked.getAttribute('data-liked-id');
                    if (!itemId) return;
                    if (!confirm('确定移除此喜欢吗？')) return;
                    try {
                        const res = await fetch(`/api/forum/likes_feed/${characterName}/${itemId}`, { method: 'DELETE' });
                        if (!res.ok) {
                            const data = await res.json().catch(()=>({error:'删除失败'}));
                            throw new Error(data.error || `HTTP ${res.status}`);
                        }
                        // 即时移除卡片
                        const card = delLiked.closest('.post');
                        if (card) card.remove();
                    } catch (err) {
                        alert(`删除失败：${err.message || err}`);
                    }
                    return;
                }

                const likeBtn = e.target.closest('.action-btn.like');
                if (likeBtn) {
                    const postElement = likeBtn.closest('.post');
                    if (!postElement) return;
                    const postId = postElement.getAttribute('data-post-id');
                    handleLikeClick(likeBtn, postId);
                    return;
                }

                const commentBtn = e.target.closest('.action-btn.comment-btn');
                if (commentBtn) {
                    const postElement = commentBtn.closest('.post');
                    if (!postElement) return;
                    const postId = postElement.getAttribute('data-post-id');
                    openReplyBox(postElement, postId);
                    return;
                }

                const replySendBtn = e.target.closest('.reply-btn');
                if (replySendBtn) {
                    const postElement = replySendBtn.closest('.post');
                    const postId = postElement.getAttribute('data-post-id');
                    const textarea = postElement.querySelector('.reply-input');
                    if (!textarea) return;
                    const content = textarea.value.trim();
                    if (!content) { alert('请输入回复内容'); return; }
                    await sendReply(postElement, postId, content, replySendBtn);
                    return;
                }

                const replyCancelBtn = e.target.closest('.reply-cancel-btn');
                if (replyCancelBtn) {
                    const postElement = replyCancelBtn.closest('.post');
                    closeReplyBox(postElement);
                    return;
                }
            });

            // 支持在回复框中 Ctrl/Cmd+Enter 提交
            postsContainer.addEventListener('keydown', async function(e) {
                if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
                    const textarea = e.target.closest('.reply-input');
                    if (textarea) {
                        const postElement = textarea.closest('.post');
                        const postId = postElement.getAttribute('data-post-id');
                        const content = textarea.value.trim();
                        if (!content) return;
                        const sendBtn = postElement.querySelector('.reply-btn');
                        await sendReply(postElement, postId, content, sendBtn);
                    }
                }
            });
        });

        async function loadExistingPosts() {
            try {
                console.log('开始请求帖子数据:', `/api/forum/posts/${characterName}`);
                const response = await fetch(`/api/forum/posts/${characterName}`);
                console.log('响应状态:', response.status);
                const data = await response.json();
                console.log('获取到的数据:', data);
                
                if (data.posts && data.posts.length > 0) {
                    displayPosts(data.posts);
                } else {
                    showEmptyState();
                }
            } catch (error) {
                console.error('获取帖子失败:', error);
                showEmptyState();
            }
        }

        async function refreshForum() {
            if (isRefreshing) return;
            
            isRefreshing = true;
            const refreshBtn = document.getElementById('refreshBtn');
            const status = document.getElementById('status');
            
            refreshBtn.disabled = true;
            refreshBtn.textContent = '✨ 拉取中...';
            status.textContent = '正在查看内心的想法...';
            
            try {
                console.log(`开始刷新推特，角色: ${characterName}`);
                
                // 创建AbortController用于超时控制
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 300000); // 5分钟超时
                
                const response = await fetch(`/api/forum/refresh/${characterName}`, {
                    method: 'POST',
                    headers: getCSRFHeaders({
                        'Content-Type': 'application/json'
                    }),
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                console.log('响应状态:', response.status);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                console.log('响应数据:', data);
                
                if (data.error) {
                    throw new Error(data.error);
                }
                
                if (data.has_new_content && data.post) {
                    // 添加新帖子到顶部
                    addNewPost(data.post);
                    status.textContent = '发布了一条新的小号动态！';
                    console.log('成功添加新帖子:', data.post);
                } else {
                    status.textContent = data.message || '暂时没有新的动态';
                    console.log('没有新内容');
                }
                
            } catch (error) {
                console.error('刷新失败:', error);
                
                if (error.name === 'AbortError') {
                    status.textContent = '发布超时，请稍后重试';
                    alert('发布超时（5分钟），可能是网络问题或AI服务响应慢，请稍后重试');
                } else {
                    status.textContent = `刷新失败: ${error.message}`;
                    alert(`刷新推特时发生错误：\n${error.message}\n\n请检查：\n1. API密钥是否配置正确\n2. 网络连接是否正常\n3. 浏览器控制台是否有更多错误信息`);
                }
            } finally {
                refreshBtn.disabled = false;
                refreshBtn.textContent = '✨ 看新动态';
                isRefreshing = false;
            }
        }

        function displayPosts(posts) {
            const container = document.getElementById('postsContainer');
            container.innerHTML = '';
            
            if (posts.length === 0) {
                showEmptyState();
                return;
            }
            
            posts.forEach(post => {
                const postElement = createPostElement(post);
                container.appendChild(postElement);
            });

            // 应用头像（若已设置）
            const savedAvatarUrl = localStorage.getItem(`avatar_${characterName}`);
            if (savedAvatarUrl) {
                updateAllPostAvatars(savedAvatarUrl);
            }
        }

        function addNewPost(post) {
            const container = document.getElementById('postsContainer');
            
            // 移除空状态显示
            const emptyState = container.querySelector('.empty-state');
            if (emptyState) {
                emptyState.remove();
            }
            
            const postElement = createPostElement(post);
            postElement.classList.add('new-post-animation');
            
            // 插入到最顶部
            container.insertBefore(postElement, container.firstChild);
            
            // 确保新帖子使用正确的头像
            let currentAvatarUrl = localStorage.getItem(`avatar_${characterName}`);
            let hasAvatar = currentAvatarUrl && currentAvatarUrl !== '';
            
            // 如果没有本地存储的头像，则检查个人资料头像
            if (!hasAvatar) {
                const profileAvatar = document.getElementById('profileAvatar');
                const profileAvatarStyle = profileAvatar.style.backgroundImage;
                currentAvatarUrl = profileAvatarStyle && profileAvatarStyle !== 'none' && profileAvatarStyle !== '' 
                    ? profileAvatarStyle.replace(/url\(['"](.+)['"]\)/, '$1') 
                    : '';
                hasAvatar = currentAvatarUrl !== '';
            }
            
            if (hasAvatar) {
                const newPostAvatar = postElement.querySelector('.post-avatar');
                if (newPostAvatar) {
                    newPostAvatar.textContent = '';
                    newPostAvatar.style.backgroundImage = `url('${currentAvatarUrl}')`;
                    newPostAvatar.style.backgroundSize = 'cover';
                    newPostAvatar.style.backgroundPosition = 'center';
                    newPostAvatar.style.backgroundRepeat = 'no-repeat';
                }
            }
        }

        function createPostElement(post) {
            const postDiv = document.createElement('div');
            postDiv.className = 'post';
            postDiv.setAttribute('data-post-id', post.id);
            
            // 处理内容格式
            let contentHtml = post.content;
            
            // 处理hashtag（将#标签高亮显示）
            contentHtml = contentHtml.replace(/#(\S+)/g, '<span class="hashtag">#$1</span>');
            
            // 处理换行
            contentHtml = contentHtml.replace(/\n/g, '<br>');
            
            const commentsHtml = post.comments && post.comments.length > 0 
                ? `<div class="comments">
                    ${post.comments.map(comment => `
                        <div class="comment">
                            <div class="comment-author">${comment.npc_name}</div>
                            <div class="comment-content">${comment.content}</div>
                            <div class="comment-time">${formatTime(comment.timestamp)}</div>
                        </div>
                    `).join('')}
                   </div>`
                : '';
            
            // 获取当前头像URL，优先从本地存储获取
            let currentAvatarUrl = localStorage.getItem(`avatar_${characterName}`);
            let hasAvatar = currentAvatarUrl && currentAvatarUrl !== '';
            
            // 如果没有本地存储的头像，则检查个人资料头像
            if (!hasAvatar) {
                const profileAvatar = document.getElementById('profileAvatar');
                const profileAvatarStyle = profileAvatar.style.backgroundImage;
                currentAvatarUrl = profileAvatarStyle && profileAvatarStyle !== 'none' && profileAvatarStyle !== '' 
                    ? profileAvatarStyle.replace(/url\(['"](.+)['"]\)/, '$1') 
                    : '';
                hasAvatar = currentAvatarUrl !== '';
            }
            
            // 创建头像元素
            let avatarHtml;
            if (hasAvatar) {
                avatarHtml = `<div class="post-avatar" style="background-image: url('${currentAvatarUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;"></div>`;
            } else {
                avatarHtml = `<div class="post-avatar">{{ character_name[0] if character_name else 'A' }}</div>`;
            }
            
            const isLiked = !!post.liked_by_me;
            postDiv.innerHTML = `
                <div class="post-content-wrapper">
                    ${avatarHtml}
                    <div class="post-main">
                        <div class="post-header">
                            <span class="post-author">{{ character_name }} 的小号</span>
                            <span class="post-handle">@{{ character_name|lower|replace(' ', '_') }}_bot</span>
                            <span class="post-time">${formatTime(post.timestamp)}</span>
                        </div>
                        <div class="post-content">${contentHtml}</div>
                        <div class="post-actions">
                            <button class="action-btn comment-btn" data-post-id="${post.id}">
                                <span class="action-icon">💬</span>
                                <span>${post.comments ? post.comments.length : 0}</span>
                            </button>
                            <button class="action-btn retweet">
                                <span class="action-icon">🔄</span>
                                <span>0</span>
                            </button>
                            <button class="action-btn like ${isLiked ? 'liked' : ''}" data-post-id="${post.id}">
                                <span class="action-icon">❤️</span>
                                <span>${post.likes || 0}</span>
                            </button>
                            <button class="action-btn share">
                                <span class="action-icon">📤</span>
                            </button>
                            <button class="action-btn delete-btn" onclick="deletePost('${post.id}')" title="删除这条动态">
                                <span class="action-icon">🗑️</span>
                            </button>
                        </div>
                        ${commentsHtml}
                    </div>
                </div>
            `;
            
            return postDiv;
        }

        function showEmptyState() {
            const container = document.getElementById('postsContainer');
            container.innerHTML = `
                <div class="empty-state">
                    <div class="empty-icon">📱</div>
                    <div class="empty-title">小号还没有动态</div>
                    <div class="empty-description">点击发布按钮，看看${characterName}最近有什么真实想法想分享</div>
                </div>
            `;
        }

        function formatTime(timestamp) {
            const date = new Date(timestamp);
            const now = new Date();
            const diff = now - date;
            
            const minutes = Math.floor(diff / 60000);
            const hours = Math.floor(diff / 3600000);
            const days = Math.floor(diff / 86400000);
            
            if (minutes < 1) return '刚刚';
            if (minutes < 60) return `${minutes}分钟前`;
            if (hours < 24) return `${hours}小时前`;
            if (days < 7) return `${days}天前`;
            
            return date.toLocaleDateString('zh-CN', {
                month: 'short',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 添加键盘快捷键支持
        document.addEventListener('keydown', function(e) {
            if (e.key === 'r' || e.key === 'R') {
                if (!isRefreshing) {
                    refreshForum();
                }
            }
        });

        // 加载“推文和回复”
        async function loadThreads() {
            try {
                const container = document.getElementById('postsContainer');
                container.innerHTML = '<div class="loading"><div class="spinner"></div><div>正在加载和你有关的会话...</div></div>';
                const response = await fetch(`/api/forum/threads/${characterName}`);
                const data = await response.json();
                if (data.posts && data.posts.length) {
                    displayThreadPosts(data.posts);
                } else {
                    container.innerHTML = '';
                    showEmptyState();
                }
            } catch (err) {
                console.error('加载会话失败:', err);
                showEmptyState();
            }
        }

        function buildCommentTree(comments) {
            const byId = new Map();
            const roots = [];
            (comments || []).forEach(c => { byId.set(c.id, { ...c, children: [] }); });
            (comments || []).forEach(c => {
                const node = byId.get(c.id);
                if (c.parent_id && byId.has(c.parent_id)) {
                    byId.get(c.parent_id).children.push(node);
                } else {
                    roots.push(node);
                }
            });
            return roots;
        }

        function displayThreadPosts(posts) {
            // 在“推文和回复”页，仅展示：回复内容 + 引用（原帖 + “我”的话）
            const container = document.getElementById('postsContainer');
            container.innerHTML = '';
            if (!posts || posts.length === 0) { showEmptyState(); return; }

            // 头像（角色）
            const currentAvatarUrl = localStorage.getItem(`avatar_${characterName}`) || '';
            const characterAvatarHtml = currentAvatarUrl
                ? (url => `<div class="post-avatar" style="background-image: url('${url}'); background-size: cover; background-position: center; background-repeat: no-repeat;"></div>`)(currentAvatarUrl)
                : `<div class="post-avatar">{{ character_name[0] if character_name else 'A' }}</div>`;

            posts.forEach(post => {
                const contentHtml = post.content.replace(/#(\S+)/g, '<span class="hashtag">#$1</span>').replace(/\n/g, '<br>');
                const roots = buildCommentTree(post.comments || []);
                // 只取“我”的一级评论及其直接AI子回复，分别生成独立卡片
                roots.forEach(root => {
                    if (root.author === 'me' && root.children && root.children.length) {
                        // 找出所有直接的AI子回复
                        root.children.filter(ch => ch.author === 'character').forEach(child => {
                            const card = document.createElement('div');
                            card.className = 'post';
                            card.innerHTML = `
                                <div class="post-content-wrapper">
                                    ${characterAvatarHtml}
                                    <div class="post-main">
                                        <div class="post-header">
                                            <span class="post-author">{{ character_name }} 的小号</span>
                                            <span class="post-time">${formatTime(child.timestamp)}</span>
                                        </div>
                                        <div class="post-content">${child.content}</div>
                                        <div class="quote-block">
                                            <div class="quote-author">我</div>
                                            <div class="quote-content">${root.content}</div>
                                            <div class="quote-content" style="margin-top:6px; border-top:1px dashed #e1e8ed; padding-top:6px;">转自：${contentHtml}</div>
                                        </div>
                                    </div>
                                </div>`;
                            container.appendChild(card);
                        });
                    }
                });
            });

            if (!container.children.length) {
                container.innerHTML = '<div class="empty-state"><div class="empty-icon">💬</div><div class="empty-title">暂无对话</div><div class="empty-description">去帖子里说点什么，回来看看TA怎么回你</div></div>';
            }
        }

        // 加载“喜欢”
        async function loadLikes() {
            try {
                const container = document.getElementById('postsContainer');
                container.innerHTML = '<div class="loading"><div class="spinner"></div><div>正在加载喜欢的内容...</div></div>';
                // 两部分：1) 我点赞的本地帖子 2) AI生成的喜欢Feed
                const [likedRes, feedRes] = await Promise.all([
                    fetch(`/api/forum/likes/${characterName}`),
                    fetch(`/api/forum/likes_feed/${characterName}`)
                ]);
                const likedData = await likedRes.json();
                const feedData = await feedRes.json();

                const likedPosts = (likedData.posts || []);
                const feedItems = (feedData.items || []);

                const containerElm = document.getElementById('postsContainer');
                containerElm.innerHTML = '';

                if (feedItems.length) {
                    // 渲染 AI 喜欢Feed，沿用帖子样式（头像+作者+内容+随机互动）
                    feedItems.forEach(item => {
                        const card = document.createElement('div');
                        card.className = 'post';
                        const avatarText = (item.author || '博主').slice(0,1);
                        const avatarHtml = `<div class="post-avatar">${avatarText}</div>`;
                        const contentHtml = (item.content || '')
                            .replace(/#(\S+)/g, '<span class="hashtag">#$1</span>')
                            .replace(/\\/g, '')
                            .replace(/\n/g, '<br>');
                        const repliesCount = (typeof item.replies === 'number') ? item.replies : Math.floor(Math.random()*120);
                        const likesCount = (typeof item.likes === 'number') ? item.likes : Math.floor(Math.random()*500) + 20;
                        card.innerHTML = `
                            <div class="post-content-wrapper">
                                ${avatarHtml}
                                <div class="post-main">
                                    <div class="post-header">
                                        <span class="post-author">${item.author || '博主'}</span>
                                        <span class="post-time">${formatTime(item.timestamp)}</span>
                                    </div>
                                    <div class="post-content">${contentHtml}</div>
                                    <div class="post-actions">
                                        <button class="action-btn comment-btn" disabled style="opacity:.6; cursor:default;">
                                            <span class="action-icon">💬</span>
                                            <span>${repliesCount}</span>
                                        </button>
                                        <button class="action-btn like" disabled style="opacity:.6; cursor:default;">
                                            <span class="action-icon">❤️</span>
                                            <span>${likesCount}</span>
                                        </button>
                                        <button class="action-btn delete-btn" title="移除此喜欢" data-liked-id="${item.id}">
                                            <span class="action-icon">🗑️</span>
                                        </button>
                                    </div>
                                </div>
                            </div>`;
                        containerElm.appendChild(card);
                    });
                }

                if (likedPosts.length) {
                    const sep = document.createElement('div');
                    sep.className = 'post';
                    sep.innerHTML = '<div class="post-content" style="color:#8899a6;">— 我点赞的帖子 —</div>';
                    containerElm.appendChild(sep);
                    likedPosts.forEach(post => containerElm.appendChild(createPostElement(post)));
                }

                if (!feedItems.length && !likedPosts.length) {
                    containerElm.innerHTML = '<div class="empty-state"><div class="empty-icon">❤️</div><div class="empty-title">还没有喜欢</div><div class="empty-description">点点红心，或点击“刷新喜欢”为你生成更懂你的内容</div></div>';
                }
            } catch (err) {
                console.error('加载喜欢失败:', err);
                showEmptyState();
            }
        }

        async function refreshLikes() {
            try {
                const btn = document.getElementById('refreshLikesBtn');
                btn.disabled = true; const oldText = btn.textContent; btn.textContent = '💖 生成中...';
                const res = await fetch(`/api/forum/refresh_likes/${characterName}`, { 
                    method: 'POST',
                    headers: getCSRFHeaders()
                });
                const ct = res.headers.get('content-type') || '';
                if (!ct.includes('application/json')) {
                    throw new Error('会话可能失效，请刷新页面后重试');
                }
                const data = await res.json();
                if (!res.ok || data.error) throw new Error(data.error || `HTTP ${res.status}`);
                // 刷新喜欢页
                await loadLikes();
            } catch (e) {
                console.error('刷新喜欢失败:', e);
                alert(`刷新喜欢失败：${e.message || e}`);
            } finally {
                const btn = document.getElementById('refreshLikesBtn');
                btn.disabled = false; btn.textContent = '💖 刷新喜欢';
            }
        }

        // 点赞处理（乐观更新）
        async function handleLikeClick(button, postId) {
            try {
                const countSpan = button.querySelector('span:last-child');
                let currentCount = parseInt(countSpan.textContent || '0', 10) || 0;
                const currentlyLiked = button.classList.contains('liked');
                const nextLiked = !currentlyLiked;

                // 乐观更新
                button.classList.toggle('liked', nextLiked);
                countSpan.textContent = String(currentCount + (nextLiked ? 1 : -1));

                // 请求后端
                const res = await fetch(`/api/forum/like/${characterName}/${postId}`, {
                    method: 'POST',
                    headers: getCSRFHeaders({ 'Content-Type': 'application/json' }),
                    body: JSON.stringify({ like: nextLiked })
                });
                if (!res.ok) throw new Error(`HTTP ${res.status}`);
                const data = await res.json();
                // 与后端结果对齐
                button.classList.toggle('liked', !!data.liked_by_me);
                countSpan.textContent = String(data.likes || 0);
            } catch (err) {
                console.error('点赞失败:', err);
                // 回滚：重新加载当前tab的内容
                if (currentTab === 'likes') {
                    loadLikes();
                } else if (currentTab === 'replies') {
                    loadThreads();
                } else {
                    loadExistingPosts();
                }
                alert('点赞失败，请稍后再试');
            }
        }

        function openReplyBox(postElement, postId) {
            // 若已存在，直接聚焦
            const existed = postElement.querySelector('.reply-box');
            if (existed) {
                const ta = existed.querySelector('.reply-input');
                if (ta) ta.focus();
                return;
            }
            const postMain = postElement.querySelector('.post-main');
            const actions = postElement.querySelector('.post-actions');
            if (!postMain || !actions) return;
            const box = document.createElement('div');
            box.className = 'reply-box';
            box.innerHTML = `
                <textarea class="reply-input" placeholder="写下你的回复...（Ctrl/⌘+Enter 发送）"></textarea>
                <div class="reply-actions">
                    <button class="reply-cancel-btn" data-post-id="${postId}">取消</button>
                    <button class="reply-btn" data-post-id="${postId}">发送</button>
                </div>
            `;
            actions.insertAdjacentElement('afterend', box);
            const ta = box.querySelector('.reply-input');
            if (ta) ta.focus();
        }

        function closeReplyBox(postElement) {
            const box = postElement.querySelector('.reply-box');
            if (box) box.remove();
        }

        async function sendReply(postElement, postId, content, btn) {
            try {
                if (btn) { btn.disabled = true; btn.textContent = '发送中...'; }
                const res = await fetch(`/api/forum/reply/${characterName}/${postId}`, {
                    method: 'POST',
                    headers: getCSRFHeaders({ 'Content-Type': 'application/json' }),
                    body: JSON.stringify({ content })
                });
                if (!res.ok) throw new Error(`HTTP ${res.status}`);
                const data = await res.json();
                const myComment = data.my_comment;
                const aiComment = data.ai_comment;

                // 如果在“推文和回复”页，直接刷新以套用Twitter式样
                if (currentTab === 'replies') {
                    await loadThreads();
                    return;
                }

                // 更新评论计数（+2）
                const commentBtn = postElement.querySelector('.action-btn.comment-btn');
                if (commentBtn) {
                    const countSpan = commentBtn.querySelector('span:last-child');
                    const cnt = parseInt(countSpan.textContent || '0', 10) || 0;
                    countSpan.textContent = String(cnt + 2);
                }

                // 添加到评论区域：先“我”的评论，再AI的回复
                let commentsWrap = postElement.querySelector('.comments');
                if (!commentsWrap) {
                    commentsWrap = document.createElement('div');
                    commentsWrap.className = 'comments';
                    const postMain = postElement.querySelector('.post-main');
                    postMain.appendChild(commentsWrap);
                }
                const myNode = document.createElement('div');
                myNode.className = 'comment';
                myNode.innerHTML = `
                    <div class="comment-author">${myComment.npc_name || '我'}</div>
                    <div class="comment-content">${myComment.content}</div>
                    <div class="comment-time">${formatTime(myComment.timestamp)}</div>
                `;
                commentsWrap.appendChild(myNode);

                const aiNode = document.createElement('div');
                aiNode.className = 'comment';
                aiNode.innerHTML = `
                    <div class="comment-author">${aiComment.npc_name || ('${characterName} 的小号')}</div>
                    <div class="comment-content">${aiComment.content}</div>
                    <div class="comment-time">${formatTime(aiComment.timestamp)}</div>
                `;
                commentsWrap.appendChild(aiNode);
                closeReplyBox(postElement);
            } catch (err) {
                console.error('发送回复失败:', err);
                alert('发送失败，请稍后重试');
            } finally {
                if (btn) { btn.disabled = false; btn.textContent = '发送'; }
            }
        }

        

        // 加载头像设置
        async function loadAvatarSettings() {
            try {
                console.log('开始加载头像设置...');
                
                // 尝试从服务器获取头像
                const response = await fetch(`/api/forum/avatar/${characterName}`);
                if (response.ok) {
                    const blob = await response.blob();
                    const avatarUrl = URL.createObjectURL(blob);
                    
                    console.log('从服务器加载头像');
                    
                    // 更新个人资料头像
                    const profileAvatar = document.getElementById('profileAvatar');
                    profileAvatar.style.backgroundImage = `url('${avatarUrl}')`;
                    profileAvatar.textContent = '';
                    
                    // 同步更新所有帖子头像
                    updateAllPostAvatars(avatarUrl);
                    
                    // 保存到本地存储（用于缓存）
                    localStorage.setItem(`avatar_${characterName}`, avatarUrl);
                } else {
                    console.log('服务器上没有找到头像文件');
                    // 清除可能过期的本地缓存
                    localStorage.removeItem(`avatar_${characterName}`);
                }
            } catch (error) {
                console.error('加载头像设置失败:', error);
                // 尝试从本地存储加载（回退机制）
                const savedAvatarUrl = localStorage.getItem(`avatar_${characterName}`);
                if (savedAvatarUrl) {
                    const profileAvatar = document.getElementById('profileAvatar');
                    profileAvatar.style.backgroundImage = `url('${savedAvatarUrl}')`;
                    profileAvatar.textContent = '';
                    updateAllPostAvatars(savedAvatarUrl);
                }
            }
        }

        // 头像编辑相关函数
        function openAvatarEdit() {
            const overlay = document.getElementById('avatarEditOverlay');
            overlay.style.display = 'flex';
        }

        // 更新所有帖子头像的函数
        function updateAllPostAvatars(avatarUrl) {
            const postAvatars = document.querySelectorAll('.post-avatar');
            postAvatars.forEach(avatar => {
                // 清除可能存在的字符内容
                avatar.textContent = '';
                // 设置背景图片样式
                avatar.style.backgroundImage = `url('${avatarUrl}')`;
                avatar.style.backgroundSize = 'cover';
                avatar.style.backgroundPosition = 'center';
                avatar.style.backgroundRepeat = 'no-repeat';
            });
            console.log(`已更新 ${postAvatars.length} 个帖子头像`);
        }

        // 清除所有帖子头像的函数
        function clearAllPostAvatars() {
            const postAvatars = document.querySelectorAll('.post-avatar');
            postAvatars.forEach(avatar => {
                // 清除背景图片样式
                avatar.style.backgroundImage = 'none';
                avatar.style.backgroundSize = '';
                avatar.style.backgroundPosition = '';
                avatar.style.backgroundRepeat = '';
                // 恢复字符头像
                avatar.textContent = '{{ character_name[0] if character_name else "A" }}';
            });
            console.log(`已清除 ${postAvatars.length} 个帖子头像`);
        }

        function closeAvatarEdit() {
            const overlay = document.getElementById('avatarEditOverlay');
            overlay.style.display = 'none';
            
            // 重置表单
            const fileInput = document.getElementById('avatarFileInput');
            const saveBtn = document.getElementById('saveAvatarBtn');
            const avatarPreview = document.getElementById('avatarPreview');
            
            fileInput.value = '';
            saveBtn.disabled = true;
            saveBtn.textContent = '上传';
            avatarPreview.style.backgroundImage = 'none';
        }

        // 预览选择的头像文件
        function previewAvatar() {
            const fileInput = document.getElementById('avatarFileInput');
            const avatarPreview = document.getElementById('avatarPreview');
            const saveBtn = document.getElementById('saveAvatarBtn');
            
            if (fileInput.files && fileInput.files[0]) {
                const file = fileInput.files[0];
                
                // 检查文件大小（5MB限制）
                if (file.size > 5 * 1024 * 1024) {
                    alert('文件大小不能超过5MB，请选择较小的图片文件');
                    fileInput.value = '';
                    saveBtn.disabled = true;
                    return;
                }
                
                // 检查文件类型
                const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
                if (!allowedTypes.includes(file.type)) {
                    alert('不支持的文件格式，请选择PNG、JPG、JPEG、GIF或WebP格式的图片');
                    fileInput.value = '';
                    saveBtn.disabled = true;
                    return;
                }
                
                // 创建预览
                const reader = new FileReader();
                reader.onload = function(e) {
                    avatarPreview.style.backgroundImage = `url('${e.target.result}')`;
                    saveBtn.disabled = false;
                };
                reader.readAsDataURL(file);
            } else {
                avatarPreview.style.backgroundImage = 'none';
                saveBtn.disabled = true;
            }
        }

        // 上传头像文件
        async function uploadAvatar() {
            try {
                const fileInput = document.getElementById('avatarFileInput');
                const saveBtn = document.getElementById('saveAvatarBtn');
                
                if (!fileInput.files || !fileInput.files[0]) {
                    alert('请先选择一个图片文件');
                    return;
                }
                
                const file = fileInput.files[0];
                const formData = new FormData();
                formData.append('avatar', file);
                
                // 更新按钮状态
                saveBtn.disabled = true;
                saveBtn.textContent = '上传中...';
                
                const response = await fetch(`/api/forum/avatar/upload/${characterName}`, {
                    method: 'POST',
                    headers: getCSRFHeaders(),
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    console.log('头像上传成功:', data);
                    
                    // 重新加载头像设置以显示新头像
                    await loadAvatarSettings();
                    
                    closeAvatarEdit();
                    alert('头像上传成功！');
                } else {
                    throw new Error(data.error || '上传失败');
                }
                
            } catch (error) {
                console.error('上传头像失败:', error);
                alert(`上传头像失败：${error.message}`);
            } finally {
                const saveBtn = document.getElementById('saveAvatarBtn');
                saveBtn.disabled = false;
                saveBtn.textContent = '上传';
            }
        }

        // 清除头像函数
        async function clearAvatar() {
            try {
                if (!confirm('确定要删除头像吗？删除后无法恢复。')) {
                    return;
                }
                
                // 调用后端API删除头像文件
                const response = await fetch(`/api/forum/avatar/${characterName}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    console.log('头像删除成功');
                    
                    // 清除本地存储
                    localStorage.removeItem(`avatar_${characterName}`);
                    
                    // 清除个人资料头像
                    const profileAvatar = document.getElementById('profileAvatar');
                    profileAvatar.style.backgroundImage = 'none';
                    profileAvatar.textContent = '{{ character_name[0] if character_name else "A" }}';
                    
                    // 清除头像预览
                    const avatarPreview = document.getElementById('avatarPreview');
                    avatarPreview.style.backgroundImage = 'none';
                    
                    // 清除所有帖子头像
                    clearAllPostAvatars();
                    
                    closeAvatarEdit();
                    alert('头像已删除！');
                } else {
                    const data = await response.json();
                    throw new Error(data.error || '删除失败');
                }
                
            } catch (error) {
                console.error('删除头像失败:', error);
                alert(`删除头像失败：${error.message}`);
            }
        }

        // 删除帖子函数
        async function deletePost(postId) {
            if (!confirm('确定要删除这条动态吗？删除后无法恢复。')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/forum/delete/${characterName}/${postId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    // 删除成功，从页面中移除帖子元素
                    const postElement = document.querySelector(`[data-post-id="${postId}"]`);
                    if (postElement) {
                        postElement.remove();
                        console.log(`帖子 ${postId} 删除成功`);
                        
                        // 检查是否还有其他帖子
                        const remainingPosts = document.querySelectorAll('.post');
                        if (remainingPosts.length === 0) {
                            showEmptyState();
                        }
                    }
                    
                    // 更新状态显示
                    const status = document.getElementById('status');
                    status.textContent = '动态删除成功！';
                    setTimeout(() => {
                        status.textContent = '点击按钮看看{{ character_name }} 有什么新想法';
                    }, 2000);
                    
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.error || '删除失败');
                }
                
            } catch (error) {
                console.error('删除帖子失败:', error);
                alert(`删除失败: ${error.message}`);
            }
        }

        // 法律声明折叠/展开功能
        document.getElementById('toggleLegal').addEventListener('click', function() {
            var content = document.getElementById('legalContent');
            if (content.style.display === 'none' || content.style.display === '') {
                content.style.display = 'block';
                this.textContent = '隐藏法律声明';
            } else {
                content.style.display = 'none';
                this.textContent = '显示法律声明';
            }
        });
    </script>
</body>
</html>
